package org.diffshop.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.diffshop.common.constant.ProductConstant;
import org.diffshop.common.utils.PageUtils;
import org.diffshop.common.utils.Query;
import org.diffshop.product.dao.PmsAttrAttrgroupRelationDao;
import org.diffshop.product.dao.PmsAttrDao;
import org.diffshop.product.dao.PmsAttrGroupDao;
import org.diffshop.product.entity.PmsAttrAttrgroupRelationEntity;
import org.diffshop.product.entity.PmsAttrEntity;
import org.diffshop.product.entity.PmsAttrGroupEntity;
import org.diffshop.product.service.PmsAttrGroupService;
import org.diffshop.product.service.PmsAttrService;
import org.diffshop.product.vo.AttrGroupWithAttrVO;
import org.diffshop.product.vo.AttrVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("pmsAttrGroupService")
public class PmsAttrGroupServiceImpl extends ServiceImpl<PmsAttrGroupDao, PmsAttrGroupEntity> implements PmsAttrGroupService {
    @Autowired
    private PmsAttrAttrgroupRelationDao relationDao;
    @Autowired
    private PmsAttrDao attrDao;
    @Autowired
    private PmsAttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PmsAttrGroupEntity> page = this.page(
                new Query<PmsAttrGroupEntity>().getPage(params),
                new QueryWrapper<PmsAttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 根据catId，获取属性分组并分页
     *
     * @param params
     * @param catId
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catId) {
        LambdaQueryWrapper<PmsAttrGroupEntity> queryWrapper = new LambdaQueryWrapper();
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            queryWrapper.and(query -> {
                query.like(PmsAttrGroupEntity::getAttrGroupName, key)
                        .or()
                        .eq(PmsAttrGroupEntity::getAttrGroupId, key);
            });
        }

        if (catId.intValue() != 0) {
            queryWrapper.eq(PmsAttrGroupEntity::getCatelogId, catId);
        }

        //todo_tjf (tjf,2024/6/12,Com_T) 校验pageIndex，limit
        Integer pageIndex = Integer.parseInt((String) params.get("page"));
        Integer limit = Integer.parseInt((String) params.get("limit"));
        Page<PmsAttrGroupEntity> page = new Page<>(pageIndex, limit);
        // 分页
        baseMapper.selectPage(page, queryWrapper);
        return new PageUtils(page);
    }

    /**
     * 获取属性分组下所有的属性
     *
     * @param attrGroupId
     * @return
     */
    @Override
    public List<AttrVO> getAttrsByAttrGroupId(Long attrGroupId) {
        // 获取属性id
        LambdaQueryWrapper<PmsAttrAttrgroupRelationEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(PmsAttrAttrgroupRelationEntity::getAttrId).eq(PmsAttrAttrgroupRelationEntity::getAttrGroupId, attrGroupId);
        List<Object> attrIds = relationDao.selectObjs(queryWrapper);

        // 封装属性列表
        List<AttrVO> attrVOList = attrIds.stream().map(attrId -> {
            PmsAttrEntity pmsAttrEntity = attrDao.selectById((Long) attrId);
            AttrVO attrVO = new AttrVO();
            if (pmsAttrEntity != null) {
                BeanUtils.copyProperties(pmsAttrEntity, attrVO);
            }
            return attrVO;
        }).collect(Collectors.toList());

        return attrVOList;
    }

    /**
     * 获取当前分组没有关联的属性
     *
     * @param params
     * @param attrGroupId
     * @return
     */
    @Override
    public PageUtils getNoAttrsByAttrGroupId(Map<String, Object> params, Long attrGroupId) {
        // 1 获取该分组所属的分类，并获取该分类下的所有分组id
        PmsAttrGroupEntity attrGroup = baseMapper.selectById(attrGroupId);

        List<Object> groupIds = baseMapper.selectObjs(new LambdaQueryWrapper<PmsAttrGroupEntity>()
                .select(PmsAttrGroupEntity::getAttrGroupId)
                .eq(PmsAttrGroupEntity::getCatelogId, attrGroup.getCatelogId()));

        // 2 获取已经和分组关联的属性id
        List<Object> relatedAttrIds = relationDao.selectObjs(new LambdaQueryWrapper<PmsAttrAttrgroupRelationEntity>()
                .select(PmsAttrAttrgroupRelationEntity::getAttrId)
                .in(PmsAttrAttrgroupRelationEntity::getAttrGroupId, groupIds));

        LambdaQueryWrapper<PmsAttrEntity> queryWrapper = new LambdaQueryWrapper<>();
        // 查询基本属性
        queryWrapper.eq(PmsAttrEntity::getAttrType, ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (relatedAttrIds != null && relatedAttrIds.size() > 0) {
            // 查询未关联的属性
            queryWrapper.eq(PmsAttrEntity::getCatelogId, attrGroup.getCatelogId())
                    .notIn(PmsAttrEntity::getAttrId, relatedAttrIds);
        } else {
            queryWrapper.eq(PmsAttrEntity::getCatelogId, attrGroup.getCatelogId());
        }

        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            queryWrapper.eq(PmsAttrEntity::getAttrId, key).or().like(PmsAttrEntity::getAttrName, key);
        }

        IPage<PmsAttrEntity> page = new Query<PmsAttrEntity>().getPage(params);
        attrDao.selectPage(page, queryWrapper);
        return new PageUtils(page);
    }

    /**
     * 查询分类下所有的属性分组及关联属性
     * @param catalogId
     * @return
     */
    @Override
    public List<AttrGroupWithAttrVO> getAttrGroupWithAttrByCatalogId(Long catalogId) {
        // 查询分类关联的属性分组
        List<PmsAttrGroupEntity> attrGroupEntities = this.list(new LambdaQueryWrapper<PmsAttrGroupEntity>().eq(PmsAttrGroupEntity::getCatelogId, catalogId));

        // 查询属性分组关联的属性
        List<AttrGroupWithAttrVO> collect = attrGroupEntities.stream().map(attrGroup -> {
            AttrGroupWithAttrVO withAttrVO = new AttrGroupWithAttrVO();
            // 封装分组信息
            BeanUtils.copyProperties(attrGroup, withAttrVO);

            // 封装属性分组的关联属性信息
            List<AttrVO> attrVOS = this.getAttrsByAttrGroupId(attrGroup.getAttrGroupId());
            withAttrVO.setAttrs(attrVOS);

            return withAttrVO;
        }).collect(Collectors.toList());

        return collect;
    }
}
